package com.hrb.mall.service.impl;

import com.hrb.mall.entity.User;
import com.hrb.mall.mapper.UserMapper;
import com.hrb.mall.service.IUserService;
import com.hrb.mall.service.ex.PasswordNotMatchException;
import com.hrb.mall.service.ex.UpdateException;
import com.hrb.mall.service.ex.UserNotFoundException;
import com.hrb.mall.service.ex.UsernameDuplicatedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

/**
 * @version 1.0
 * @Author YangJiaQuan_hrbnu
 * @Date 2023/9/22 11:12
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void reg(User user) {
        String username = user.getUsername();
        User result = userMapper.findByUsername(username);
        //判断是否为null
        if(result != null){
            throw new UsernameDuplicatedException("用户名被占用");
        }
        //加密处理 md5
        //加密形式：串+password+串——》md5加密循环3次

        String oldPassword = user.getPassword();
        //随机生成串
        String salt = UUID.randomUUID().toString().toUpperCase();
        user.setSalt(salt);
        //加密
        String md5Password = getMD5Password(oldPassword,salt);

        user.setPassword(md5Password);

        //补全数据 iddelete==0，四个日志
        user.setIsDelete(0);
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);

        //执行注册(rows==1)
        Integer rows = userMapper.insert(user);
        if(rows != 1){
            throw new UsernameDuplicatedException("用户注册过程中产生了未知异常");
        }
    }

    @Override
    public User login(String username, String password) {
        //根据用户名称来查询用户的数据是否存在，如果不在则抛出异常
        User result = userMapper.findByUsername(username);
        if (result == null) {
            throw  new UserNotFoundException("用户数据不存在");
        }
        // 检测用户的密码是否匹配
        String oldPassword = result.getPassword();

        String salt = result.getSalt();

        String newMd5Passord = getMD5Password(password, salt);

        if (!newMd5Passord.equals(oldPassword)) {
            throw new PasswordNotMatchException("用户密码错误");
        }

        // 判断is_delete字段的值是否为1表示被标记为删除
        if (result.getIsDelete() == 1){
            throw new UserNotFoundException("用户数据不存在");
        }

        // 调用mapper层的findByUsername来查询用户的数据
        User user = new User();
        user.setUid(result.getUid());
        user.setUsername(result.getUsername());
        user.setAvatar(result.getAvatar());

        // 将当前用户数据返回，辅助其他页面做数据展示使用（uid,username,avatar)
        return user;
    }

    @Override
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword) {
        User result = userMapper.findByUid(uid);
        if(result == null || result.getIsDelete() == 1){
            throw new UserNotFoundException("用户数据不存在");
        }
        //原始密码与老密码进行比较
        String oldMd5Password = getMD5Password(oldPassword,result.getSalt());
        if(!result.getPassword().equals(oldMd5Password)){
            throw new PasswordNotMatchException("密码错误！！");
        }
        //将新密码设计到数据库中==加密在更新
        String newMd5Password = getMD5Password(newPassword, result.getSalt());
        Integer rows = userMapper.updatePasswordByUid(uid,newMd5Password,username,new Date());

        if(rows != 1){
            throw new UpdateException("更新数据时产生未知的异常");
        }

    }

    @Override
    public User getByUid(Integer uid) {
        User result = userMapper.findByUid(uid);
        if(result==null || result.getIsDelete()==1){
            throw new UserNotFoundException("用户数据不存在");
        }
        User user = new User();
        user.setUsername(result.getUsername());
        user.setPhone(result.getPhone());
        user.setEmail(result.getEmail());
        user.setGender(result.getGender());

        return user;
    }

    @Override
    /**
     * User对象中的数据phone\email\gender
     */
    public void changeInfo(Integer uid, String username, User user) {
        User result =  userMapper.findByUid(uid);
        if(result==null || result.getIsDelete()==1){
            throw new UserNotFoundException("用户数据不存在");
        }
        user.setUid(uid);
        //user.getUsername(username);
        user.setModifiedUser(username);
        user.setModifiedTime(new Date());

        Integer rows = userMapper.updateInfoByUid(user);
        if(rows != 1){
            throw new UpdateException("更新数据产生未知的异常");
        }
    }

    @Override
    public void changeAvatar(Integer uid, String avatar, String username) {
        // 查询当前的用户数据是否存在
        User result = userMapper.findByUid(uid);
        if(result==null || result.getIsDelete().equals(1)){
            throw new UserNotFoundException("用户数据不存在");
        }
        Integer rows = userMapper.updateAvatarByUid(uid,avatar,
                username,new Date());
        if (rows!=1){
            throw new UpdateException("更新用户头像产生未知的异常");
        }

    }


    private String getMD5Password(String password,String salt){
        for (int i = 0; i < 3; i++) {
            //MD5加密算法调用，三次加密
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        return password;
    }
}
